package com.example.demo.service.impl;

import com.example.demo.response.UserVO;
import com.example.demo.service.PdfService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class PdfServiceImpl implements PdfService {
    @Override
    public List<UserVO> analysisPdf(MultipartFile file) {

        //https://www.python100.com/html/106173.html
//        JsonObject
        List<UserVO> list = new ArrayList<>();
        try (PDDocument document = PDDocument.load(file.getInputStream())) {
            PDFTextStripper stripper = new PDFTextStripper();
            String content = stripper.getText(document).trim();

            String[] split1 = content.split("\r\n");
            int firstIndex = 0;
            for (String row : split1) {
                if(0 == firstIndex++)
                    continue;
                UserVO userVO = new UserVO();
                String[] split2 = row.split(" ");

                userVO.setName(split2[0]);
                userVO.setSex(split2[1]);
                userVO.setAge(split2[2]);
                userVO.setAddress(split2[3]);
                list.add(userVO);

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
        /*

        PDFTableExtractor extractor = new PDFTableExtractor();
        List<PDFTable> tables = extractor.setSource(document).extract();
        for (PDFTable table : tables) {
            for (List<PDFCell> row : table.getRows()) {
                for (PDFCell cell : row) {
                    System.out.print(cell.getText() + "\t\t");
                }
                System.out.println();
            }
        }*/
    }
}
